package umodels

import (
	"github.com/astaxie/beego/orm"
	"cloud_worm/util/umodels/mysqldb"
	"fmt"
	"strings"
	_ "github.com/go-sql-driver/mysql"
	_ "cloud_worm/util/umodels/mysqldb/dbdata"
	_ "cloud_worm/util/umodels/mysqldb/dbmanager"
	_ "cloud_worm/util/umodels/mysqldb/dbmonitor"
	_ "cloud_worm/util/umodels/mysqldb/dbtask"
	"log"
)

type DbInfo struct {
	RunMode 	string

	UserName 	string
	Password 	string
	Domain 		string
	Port 		string
	Database 	string
}

func OrmInit(dbInfo DbInfo)  {
	err := orm.RegisterDriver(mysqldb.DBDriver, orm.DRMySQL)
	if err != nil {
		panic(err)
	}

	dbUrl := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8",
		dbInfo.UserName, dbInfo.Password, dbInfo.Domain, dbInfo.Port, dbInfo.Database)
	log.Println(dbUrl)

	err = orm.RegisterDataBase(mysqldb.DefaultDataBase, mysqldb.DBDriver, dbUrl, 30)
	if err != nil {
		panic(err)
	}
	orm.SetMaxIdleConns(mysqldb.DefaultDataBase, 30)
	orm.SetMaxOpenConns(mysqldb.DefaultDataBase, 100)
	err = orm.RunSyncdb(mysqldb.DefaultDataBase, false, false)
	if err != nil {
		panic(err)
	}

	if strings.HasPrefix(dbInfo.RunMode, "dev") {
		orm.Debug = true
		defaultDB, err := orm.GetDB(mysqldb.DefaultDataBase)
		if err != nil {
			panic(err)
		}
		defaultDB.SetConnMaxLifetime(0)
	} else {
		orm.Debug = false
	}

	log.Println("connect to mysql OK!!!")
	return
}
